#include <random>
#include "Socket.hpp"
#include "Log.hpp"
#include "Protcol.hpp"

int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        LOG(FATAL, "too few arguments!\n");
        exit(0);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    SockPtr client = std::make_shared<tcp_Socket>();
    if (!client->BuildClientSocket(ip, port))
    {
        LOG(FATAL, "connect error!\n");
        exit(1);
    }

    srand(time(nullptr));
    const std ::string opers = "+-*/%&^!";

    int cnt = 3;
    std::string packagestreamqueue;
    while (true)
    {
        // 构建数据
        int x = rand() % 10;
        usleep(x * 1000);
        int y = rand() % 10;
        usleep(x * y * 100);
        char oper = opers[y % 5];

        // 构建请求
        auto req = Factory::BuildRequestDefault();
        req->SetValue(x, y, oper);
        std::cout << "####################################" << std::endl;
        req->Print();
        
        // 序列化和拼接报文
        std::string jsonstr;
        req->Serialize(&jsonstr);
        jsonstr = Encode(jsonstr);


        std::cout << "request string: \n"
                  << jsonstr << std::endl;

        // 发送报文
        client->Send(jsonstr);

        // 获取报文
        while (true)
        {
            ssize_t n = client->Recv(&packagestreamqueue);
            if(n<=0)
            {
                break;
            }

            
            // 拆封报文和反序列化
            std::string package;
            package = Decode(packagestreamqueue);
            if(package.empty())
            {
                continue;
            }
            std::cout << "package: \n" << package << std::endl;

            // 构建响应
            auto resp = Factory::BuildResponseDefault();
            resp->Deserialize(package);

            // 打印结果
            resp->PrintResult();
            break;
        }
        sleep(1);
    }
    client->Close();
}